//
//  StatusListViewModel.swift
//  sinaweibowj
//
//  Created by Macintosh on 15/12/22.
//  Copyright © 2015年 mactoinsh. All rights reserved.
//

import UIKit
import SVProgressHUD

class StatusListViewModel: NSObject {

    //since_id 新的微博字段 ，实现下拉刷新
    class func loadHomePageData(since_id:Int64,max_id:Int64, finished:(statuses:[Status]?) -> ()) {
    
        //实现网络请求
        
        let urlString = "2/statuses/home_timeline.json"
        //判断token是否为空
        guard let token = UserAccountViewModel().token else{
            print("token为空")
            SVProgressHUD.showInfoWithStatus("请重新登录")
            return
        }
        var   parameters = ["access_token":token]
        if since_id > 0 {
        parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        //发送请求
        NetWorkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil {
                //请求失败的回调
                print(error)
                SVProgressHUD.showInfoWithStatus("网络出错")
                finished(statuses: nil)
                return
                
            }
            //算数据获取成功
            //通过键值的方式，获取statuses对应的数据
            var list = [Status]()
            
            if let array = dict!["statuses"] as? [[String:AnyObject]] {
                //print(array)
                //TODO:遍历数组中所有字典，做字典转模型操作
                for item in array {
                    let s = Status(dict:item)
                    list.append(s)
                }
               //执行成功的回调
                finished(statuses: list)
            }
    }
    
}
}